const db_promise = require("../config/db.config.js");
const logger = require('../util/logger');

module.exports = {
  getLogs,
  logRequest,
  getRequestUsageTotal,
  getTotalLogEntries,
  getIntentUsageByDay
};


async function getRequestUsageTotal(req, res, next) {
	
	
  try {
    	
    	 const [rows,fields] = await db_promise.query("select count(*) as count from nlu_log where event_type = 'parse'" );
    	 
    	 console.log(rows);
    	 
    	 res.status(200).json({total_request_usage: rows[0].count});
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  } 	
	

}

async function getTotalLogEntries(req, res, next) {
	
	
  try {
    	
    	 const [rows,fields] = await db_promise.query("select count(*) as count from nlu_log" );
    	 
    	 console.log(rows);
    	 
    	 res.status(200).json({total_log_entries: rows[0].count});
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  } 		
	

}

async function getIntentUsageByDay(req, res, next) {
	
  try {
    	
    	 const [rows,fields] = await db_promise.query("select DATE_FORMAT(timestamp,'%m/%d')  as day, count(*) as cnt from nlu_log group by  DATE_FORMAT(timestamp,'%m/%d')" );
    	 
    	 console.log(rows);
    	 
    	 res.status(200).json(rows);
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  } 		
	

}




async function logRequest(req, type, data) {
	
  try {
    const obj = {};
    obj.ip_address = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    obj.query = req.originalUrl;
    obj.event_type = type;
    obj.event_data = JSON.stringify(data);
    
    const [rows, fields] = await db_promise.execute("insert into nlu_log (ip_address, query, event_type, event_data) values (?,?,?,?)",[obj.ip_address, obj.query, obj.event_type, obj.event_data]);
    
  	console.log(rows);
  	    

  } catch (err) {
    logger.winston.info('Error: ' + err);
    
 	     
    
  }
}

async function getLogs(req, res, next) {
	
  try {	
  	
	  const [rows,fields] = await db_promise.query("select * from nlu_log where event_type = ? order by timestamp desc",[req.params.query]);
	
	  res.status(200).json(rows);
  
  }catch(err){
  	
    logger.winston.info('Error: ' + err);
    
    res.status(400).send({
      message: err
    });  

	}
  
  
  
}
